import { encode, decode } from 'js-base64';
import { ElMessage } from "element-plus";
import { uniq } from "underscore";
import Studycodemodel from "../mysql_interface/studycodemodel";
interface Iarr {
  [key: string]: any, pid?: number, ID?: number, children?: Iarr[]
}
export function findpid<T extends Iarr = Iarr>(data: Array<T>, id?: number) {
  data = JSON.parse(JSON.stringify(data))
  const arr: Array<T> = []
  for (const v in data) {
    if (data[v].pid == id) {
      data[v].children = uniq(findpid(data, data[v].ID))
      arr.push(data[v])
    }
  }
  return arr
}

export function flattenpid<T extends Iarr = Iarr>(data: Array<T>, arr: Array<T> = []) {
  data = JSON.parse(JSON.stringify(data))
  for (const i in data) {
    const value = data[i].children || []
    if (value.length) {
      flattenpid(value, arr)
    }
    arr.push(data[i])
  }
  return arr;
}

export function getpidtoarr<T extends Iarr = Iarr>(data: Array<number>, arr: T[]) {
  return data.map(e => {
    let r: number[] = [e]
    while (true) {
      const t = arr.find(f => f.ID === r[0])
      if (!t) return r
      if (t.pid) {
        r = [t.pid].concat(...r)
      } else {
        return r
      }
    }
  })
}


/**
 * 平均生成分数
 */
export function settestcasesscore(testcases: Studycodemodel.Itestcases[]): Studycodemodel.Itestcases[] {
  const length = testcases?.length;
  if (length) {
    const score = Math.floor(100 / length);
    const yu = 100 % length;
    return testcases?.map((e, k) => {
      let n = 0;
      if (k > length - yu - 1) {
        n = n + 1;
      }
      return {
        ...e,
        score: score + n,
      };
    });
  }
  return testcases
}

export function download2(row: Studycodemodel.Iuserquestion) {
  const { context, language, user } = row;
  if (context) {
    window.open(`https://cdn.hterobot.com/diffeditor/index.html?code1=${encode(context, true)}&language=${language}&name1=${encodeURI(user?.name)}`)
  } else {
    ElMessage.error("代码为空");
  }
}


export function time(
  info: Studycodemodel.Iuserquestion["info"]) {
  if (!Array.isArray(info)) return NaN;
  let t = 0;
  for (let v of info) {
    if (t < Number(v.t)) {
      t = Number(v.t);
    }
  }
  return Math.floor(t) + "ms";
}

export function memory(
  info: Studycodemodel.Iuserquestioninfo) {
  if (typeof info.memory === "number") {
    return info.memory / 1024 < 1
      ? Math.floor(info.memory) + "kb"
      : Math.floor(info.memory / 1024) + "mb";
  } else if (typeof info.memory === "object") {
    return "4kb";
  }
  return info.memory || "4kb";
}